package foodmaterial.action;

import foodmaterial.entity.JsonResult;
import foodmaterial.entity.SysUser;
import foodmaterial.service.InitService;
import foodmaterial.utils.Constants;
import foodmaterial.utils.SnowflakeWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RequestMapping("/api/upload")
@RestController
@CrossOrigin(allowCredentials = "true")
public class UploadAction extends BaseAction {

    @Autowired
    private SnowflakeWorker worker ;

    @Autowired
    private InitService initService ;

    private JsonResult<String> upload(String type,MultipartFile file) throws Exception {
        JsonResult<String> result = new JsonResult<>() ;
        result.setSuccess(true);
        String folder = initService.querySysParamsByCode(type).getParamValue();
        folder += this.getSysUser().getDb() ;
        File imageFolder = new File(folder);
        File f = new File(imageFolder, worker.nextId() + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists()) f.getParentFile().mkdirs();
        file.transferTo(f);
        String imgURL = f.getName();
        result.setData(imgURL);
        return result;
    }

    @PostMapping("/credentials")
    public JsonResult<String> credentialsUpload(MultipartFile file) throws Exception {
        return upload(Constants.CREDENTIALS_PATH,file) ;
    }

    @PostMapping("/foodMaterial")
    public JsonResult<String> foodMaterialUpload(MultipartFile file) throws Exception {
        return upload(Constants.FOOD_PATH,file) ;
    }

    @PostMapping("/testReport")
    public JsonResult<String> testReportUpload(MultipartFile file) throws Exception {
        return upload(Constants.TEST_REPORT_PATH,file) ;
    }

    @PostMapping("/recipeTemplate")
    public JsonResult<String> recipeTemplateUpload(MultipartFile file) throws Exception {
        return upload(Constants.RECIPE_IMAGE_PATH,file) ;
    }
}
